package com.aiti.lulian.service.newCard;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.constant.MiniProgramVersionConstant;
import com.aiti.lulian.constant.NewCardBusinessConstant;
import com.aiti.lulian.dto.newCard.CardShareConfig;
import com.aiti.lulian.dto.newCard.CardTemplateStyleFieldBo;
import com.aiti.lulian.dto.newCard.EnterpriseCardAddParamDto;
import com.aiti.lulian.dto.newCard.EnterpriseMiniVersionDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.entity.newCard.*;
import com.aiti.lulian.gxmh.dto.SysUserDto;
import com.aiti.lulian.mapper.*;
import com.aiti.lulian.mapper.gxmh.GxmhSysMapper;
import com.aiti.lulian.mapper.newCard.*;
import com.aiti.lulian.service.CardTemplateStyleFieldService;
import com.aiti.lulian.service.CardUserCardForwardCoverOptionService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * description:
 * auth fcb
 * date 2025-08-18 11:31TE
 **/
@Service
@Slf4j
public class EnterpriseNewCardService {

    // 本地开发环境默认模板id e0cb2cad-8ba0-497a-847c-d42823dbf0c8
    private static final String DEFAULT_CARD_TEMPLATE_ID = "b8e1d53e0f96434bbf40aae5d5341d7a";

    @Autowired
    private CardPersonalBaseInfoService cardPersonalBaseInfoService;
    @Autowired
    private CardPersonalBaseInfoMapper cardPersonalBaseInfoMapper;
    @Autowired
    private CardDescriptionService cardDescriptionService;
    @Autowired
    private CardDescriptionMapper cardDescriptionMapper;
    @Autowired
    private CardLinkInfoService cardLinkInfoService;
    @Autowired
    private CardLinkInfoMapper cardLinkInfoMapper;
    @Autowired
    private CardMoreInfoService cardMoreInfoService;
    @Autowired
    private CardMoreInfoMapper cardMoreInfoMapper;
    @Autowired
    private CardPersonalFileInfoService cardPersonalFileInfoService;
    @Autowired
    private CardPersonalFileInfoMapper cardPersonalFileInfoMapper;
    @Autowired
    private CardVideoInfoService cardVideoInfoService;
    @Autowired
    private CardVideoInfoMapper cardVideoInfoMapper;
    @Autowired
    private CardUserCardSettingMapper cardUserCardSettingMapper;
    @Autowired
    private CardVersionService cardVersionService;
    @Autowired
    private NewCardVersionMapper newCardVersionMapper;
    @Autowired
    private CardOperationLogMapper cardOperationLogMapper;
    @Autowired
    private LuLianEnterpriseUserMapper luLianEnterpriseUserMapper;
    @Autowired
    private LuLianEnterpriseHistoryMapper luLianEnterpriseHistoryMapper;
    @Autowired
    private LuLianEnterpriseMapper luLianEnterpriseMapper;
    @Autowired
    private GxmhSysMapper gxmhSysMapper;
    @Autowired
    private ShowEnterpriseTrialMapper showEnterpriseTrialMapper;
    @Autowired
    private CardEnterpriseTemplateNewMapper cardEnterpriseTemplateNewMapper;
    @Autowired
    private CardEnterpriseComponentMapper cardEnterpriseComponentMapper;
    @Autowired
    private CardEnterpriseComponentService cardEnterpriseComponentService;
    @Autowired
    private CardComponentDataMapper cardComponentDataMapper;
    @Autowired
    private CardComponentDataService cardComponentDataService;
    @Autowired
    private CardEnterpriseTemplateMapper cardEnterpriseTemplateMapper;
    @Autowired
    private CardStyleFieldDataService cardStyleFieldDataService;
    @Autowired
    private CardTemplateStyleFieldService cardTemplateStyleFieldService;
    @Autowired
    private CardTemplateStyleFieldMapper cardTemplateStyleFieldMapper;
    @Autowired
    private CardAuditService cardAuditService;
    @Autowired
    private CardShareConfigService cardShareConfigService;
    @Autowired
    private CardUserCardForwardCoverOptionService cardUserCardForwardCoverOptionService;
    @Autowired
    private CardPrivacySettingMapper cardPrivacySettingMapper;

    /**
     * 查询名片状态
     * @param cardId
     * @return
     */
    public Integer getEnterpriseCardStatus(String cardId) {
        if(StrUtil.isBlank(cardId)) {
            throw new BusinessException("参数错误");
        }
        CardAudit cardAudit = cardAuditService.queryCardAuditInfoByCardId(cardId);
        if(cardAudit == null) {
            throw new BusinessException("未查询到名片状态，该名片不存在或不是企业名片");
        }
        return cardAudit.getCardStatus();
    }

    /**
     * 查询用户是否已经申请过试用
     * 后台添加企业名片的时候，增加一条试用记录
     * @param userId
     * @return
     */
    public Boolean queryTryUserCount(String userId) {
        // 查询当前用户是否有企业名片，有企业名片且没过期，无法试用。有企业名片过期了，判断有没有试用过
        // 0:个人试用版，1：企业试用版
        return newCardVersionMapper.queryTryUserCount(userId, 1) > 0;
    }

    /**
     * 领取企业名片。
     * 这个接口的调用入口只有两个：1.首次试用企业功能；2.用户已经申请过试用，在企业名片主页创建新的企业
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    public Message addEnterpriseCard(EnterpriseCardAddParamDto dto) {
        this.checkEnterpriseCardParam(dto);
        // 查询当前用户的企业名片是否存在了同名的名片
        Integer sameNameCount = cardPersonalBaseInfoMapper.queryCountByUserIdAndEnterpriseName(dto.getUserId(), dto.getEnterpriseName());
        if(sameNameCount > 0) {
            return Message.fail("您已创建过同名的的企业名片");
        }
        DateTime newExpireTime = DateUtil.offsetDay(new Date(), 7);
        EnterpriseMiniVersionDto enterpriseMiniVersion = luLianEnterpriseMapper.queryMiniVersion(dto.getEnterpriseName());
        // todo 这里是否需要考虑正在使用，正在试用，使用到期的情况
        if(enterpriseMiniVersion != null) {
            List<String> enterpriseAdminUserIdList = luLianEnterpriseMapper.queryEnterpriseAdminUserIdList(enterpriseMiniVersion.getBaseId());
            if(CollectionUtil.isEmpty(enterpriseAdminUserIdList)) {
                return Message.fail("该企业为认证企业。但未查询到企业管理员，请联系相关人员处理");
            }else {
                String enterpriseAdminUserId = enterpriseAdminUserIdList.get(0);
                SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(enterpriseAdminUserId);
                Map<String, String> map = new HashMap<>();
                map.put("adminFirstName", StrUtil.isBlank(sysUserDto.getRealname()) ? "" : sysUserDto.getRealname().substring(0,1));
                map.put("position", StrUtil.isBlank(sysUserDto.getPosition()) ? "" : sysUserDto.getPosition());
                map.put("enterpriseName", StrUtil.isBlank(enterpriseMiniVersion.getEnterpriseName()) ? "" : enterpriseMiniVersion.getEnterpriseName());
                return Message.exception(map);
            }
        }
        else {
            // 0. 查询默认模板id
            String defaultTemplateId = cardEnterpriseTemplateNewMapper.queryDefaultTemplateId();
            if(StrUtil.isBlank(defaultTemplateId)) {
                throw new BusinessException("未查询到配置的默认模板");
            }
            // 1. 创建企业数据并设置版本
            LuLianEnterpriseHistory luLianEnterpriseHistory = this.buildEnterpriseHistoryInfo(dto);
            //luLianEnterpriseHistoryMapper.insert(luLianEnterpriseHistory);
            LuLianEnterprise luLianEnterprise = new LuLianEnterprise();
            BeanUtil.copyProperties(luLianEnterpriseHistory, luLianEnterprise);
            luLianEnterprise.setMiniProgramVersion(MiniProgramVersionConstant.SHI_YONG_VERSION);
            luLianEnterprise.setExpireTime(newExpireTime);
            luLianEnterprise.setNewCardTrialVersion(1);
            //luLianEnterpriseMapper.insert(luLianEnterprise);
            ShowEnterpriseTrial showEnterpriseTrial = new ShowEnterpriseTrial();
            BeanUtil.copyProperties(luLianEnterprise, showEnterpriseTrial);
            showEnterpriseTrialMapper.insert(showEnterpriseTrial);
            // 2. 绑定企业
            this.bindEnterprise(luLianEnterprise.getBaseId(), dto.getUserId());
            // 3. 设置企业管理员
            this.setEnterpriseAdmin(dto.getUserId(), showEnterpriseTrial.getBaseId());

            // 4. 根据默认模板创建当前企业的一个模板。现在有两个模板表：card_enterprise_template_new，card_enterprise_template
            String templateId = this.createTemplateNew(showEnterpriseTrial.getBaseId(), dto, defaultTemplateId);
            // 4.1 设置新模板的组件数据
            List<CardEnterpriseComponent> templateComponentData = this.createTemplateComponentData(templateId, defaultTemplateId);
            // 创建模板的分享配置
            CardShareConfig cardShareConfig = cardShareConfigService.buildCardShareConfig(showEnterpriseTrial.getBaseId(), templateId);
            cardShareConfigService.save(cardShareConfig);
            // 4.2 生成一张企业名片信息
            dto.setEnterpriseId(showEnterpriseTrial.getBaseId());
            CardBaseInfo cardBaseInfo = this.buildEnterpriseCardInfo(dto, newExpireTime);
            cardBaseInfo.setTemplateId(templateId);
            cardPersonalBaseInfoService.save(cardBaseInfo);
            // 4.2.1 初始化名片隐私设置
            cardPrivacySettingMapper.insert(CardPrivacySetting.builder().baseId(IdUtil.simpleUUID()).userId(cardBaseInfo.getUserId()).cardId(cardBaseInfo.getBaseId()).baseUpdateTime(new Date()).build());
            // 4.3 给当前企业生成旧的模板表数据 （生成card_enterprise_template数据）
            CardEnterpriseTemplate oldTemplateTableData = this.createTemplate(showEnterpriseTrial.getBaseId(), dto, templateId, defaultTemplateId);
            cardEnterpriseTemplateMapper.insert(oldTemplateTableData);
            // 4.4 根据预设模板创建卡片字段数据
            List<CardTemplateStyleField> templateStyleFieldList = this.createTemplateStyleField(oldTemplateTableData.getBaseId(), dto.getUserId(), defaultTemplateId, dto);

            // 5. 根据上面的模板，生成名片的具体数据，包括卡片字段和组件
            // 5.1 生成名片的卡片数据。根据表单里面填写的数据和默认模板上的字段属性按名字匹配，只保存能匹配上的
            this.createStyleFieldData(dto, cardBaseInfo.getBaseId(), templateStyleFieldList);
            // 5.2 生成名片的组件数据
            this.createCardComponentData(templateComponentData, cardBaseInfo.getBaseId());
            // 生成名片的转发封面
            this.cardUserCardForwardCoverOptionService.createDefaultForwardCover(dto.getUserId(), cardBaseInfo.getBaseId(), cardShareConfig.getCoverUrl(), cardShareConfig.getType(), cardShareConfig.getCoverUrlBaseId());
            // 6. 将当前生成的名片设置为自动审核通过
            this.auditPass(luLianEnterprise.getBaseId(), templateId, cardBaseInfo.getBaseId(), dto.getUserId());
        }
        return Message.success();
    }

    public Message existSameEnterpriseCard(EnterpriseCardAddParamDto dto) {
        // 查询当前用户的企业名片是否存在了同名的名片
        Integer sameNameCount = cardPersonalBaseInfoMapper.queryCountByUserIdAndEnterpriseName(dto.getUserId(), dto.getEnterpriseName());
        if(sameNameCount > 0) {
            return Message.fail("您已创建过同名的的企业名片");
        }
        DateTime newExpireTime = DateUtil.offsetDay(new Date(), 7);
        EnterpriseMiniVersionDto enterpriseMiniVersion = luLianEnterpriseMapper.queryMiniVersion(dto.getEnterpriseName());
        // todo 这里是否需要考虑正在使用，正在试用，使用到期的情况
        if(enterpriseMiniVersion != null) {
            List<String> enterpriseAdminUserIdList = luLianEnterpriseMapper.queryEnterpriseAdminUserIdList(enterpriseMiniVersion.getBaseId());
            if(CollectionUtil.isEmpty(enterpriseAdminUserIdList)) {
                return Message.fail("该企业为认证企业。但未查询到企业管理员，请联系相关人员处理");
            }else {
                String enterpriseAdminUserId = enterpriseAdminUserIdList.get(0);
                SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(enterpriseAdminUserId);
                Map<String, String> map = new HashMap<>();
                map.put("adminFirstName", StrUtil.isBlank(sysUserDto.getRealname()) ? "" : sysUserDto.getRealname().substring(0,1));
                map.put("position", StrUtil.isBlank(sysUserDto.getPosition()) ? "" : sysUserDto.getPosition());
                map.put("enterpriseName", StrUtil.isBlank(enterpriseMiniVersion.getEnterpriseName()) ? "" : enterpriseMiniVersion.getEnterpriseName());
                return Message.exception(map);
            }
        }
        return Message.success();
    }

    public Message addNewEnterpriseCard(EnterpriseCardAddParamDto dto) {
        this.checkEnterpriseCardParam(dto);
        // 查询当前用户的企业名片是否存在了同名的名片
        Integer sameNameCount = cardPersonalBaseInfoMapper.queryCountByUserIdAndEnterpriseName(dto.getUserId(), dto.getEnterpriseName());
        if(sameNameCount > 0) {
            return Message.fail("您已创建过同名的的企业名片");
        }
        DateTime newExpireTime = DateUtil.offsetDay(new Date(), 7);
        EnterpriseMiniVersionDto enterpriseMiniVersion = luLianEnterpriseMapper.queryMiniVersion(dto.getEnterpriseName());
        // todo 这里是否需要考虑正在使用，正在试用，使用到期的情况
        if(enterpriseMiniVersion != null) {
            List<String> enterpriseAdminUserIdList = luLianEnterpriseMapper.queryEnterpriseAdminUserIdList(enterpriseMiniVersion.getBaseId());
            if(CollectionUtil.isEmpty(enterpriseAdminUserIdList)) {
                return Message.fail("该企业为认证企业。但未查询到企业管理员，请联系相关人员处理");
            }else {
                String enterpriseAdminUserId = enterpriseAdminUserIdList.get(0);
                SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(enterpriseAdminUserId);
                Map<String, String> map = new HashMap<>();
                map.put("adminFirstName", StrUtil.isBlank(sysUserDto.getRealname()) ? "" : sysUserDto.getRealname().substring(0,1));
                map.put("position", StrUtil.isBlank(sysUserDto.getPosition()) ? "" : sysUserDto.getPosition());
                map.put("enterpriseName", StrUtil.isBlank(enterpriseMiniVersion.getEnterpriseName()) ? "" : enterpriseMiniVersion.getEnterpriseName());
                return Message.exception(map);
            }
        }
        else {
            // 0. 查询默认模板id
            String templateId = dto.getTemplateId();

            // 1. 创建企业数据并设置版本
            LuLianEnterpriseHistory luLianEnterpriseHistory = this.buildEnterpriseHistoryInfo(dto);
            //luLianEnterpriseHistoryMapper.insert(luLianEnterpriseHistory);
            LuLianEnterprise luLianEnterprise = new LuLianEnterprise();
            BeanUtil.copyProperties(luLianEnterpriseHistory, luLianEnterprise);
            luLianEnterprise.setMiniProgramVersion(MiniProgramVersionConstant.SHI_YONG_VERSION);
            luLianEnterprise.setExpireTime(newExpireTime);
            luLianEnterprise.setNewCardTrialVersion(1);
            //luLianEnterpriseMapper.insert(luLianEnterprise);
            ShowEnterpriseTrial showEnterpriseTrial = new ShowEnterpriseTrial();
            BeanUtil.copyProperties(luLianEnterprise, showEnterpriseTrial);
            showEnterpriseTrialMapper.insert(showEnterpriseTrial);
            // 2. 绑定企业
            this.bindEnterprise(luLianEnterprise.getBaseId(), dto.getUserId());
            // 3. 设置企业管理员
            this.setEnterpriseAdmin(dto.getUserId(), showEnterpriseTrial.getBaseId());

            // 4. 根据默认模板创建当前企业的一个模板。现在有两个模板表：card_enterprise_template_new，card_enterprise_template
            //String templateId = this.createTemplateNew(showEnterpriseTrial.getBaseId(), dto, defaultTemplateId);
            // 4.1 设置新模板的组件数据
            //List<CardEnterpriseComponent> templateComponentData = this.createTemplateComponentData(templateId, defaultTemplateId);
            // 创建模板的分享配置
            CardShareConfig cardShareConfig = cardShareConfigService.buildCardShareConfig(showEnterpriseTrial.getBaseId(), templateId);
            cardShareConfigService.save(cardShareConfig);
            // 4.2 生成一张企业名片信息
            dto.setEnterpriseId(showEnterpriseTrial.getBaseId());
            CardBaseInfo cardBaseInfo = this.buildEnterpriseCardInfo(dto, newExpireTime);
            cardBaseInfo.setTemplateId(templateId);
            cardPersonalBaseInfoService.save(cardBaseInfo);
            // 4.2.1 初始化名片隐私设置
            cardPrivacySettingMapper.insert(CardPrivacySetting.builder().baseId(IdUtil.simpleUUID()).userId(cardBaseInfo.getUserId()).cardId(cardBaseInfo.getBaseId()).baseUpdateTime(new Date()).build());
            // 4.3 给当前企业生成旧的模板表数据 （生成card_enterprise_template数据）
            //CardEnterpriseTemplate oldTemplateTableData = this.createTemplate(showEnterpriseTrial.getBaseId(), dto, templateId, defaultTemplateId);
            //cardEnterpriseTemplateMapper.insert(oldTemplateTableData);
            // 4.4 根据预设模板创建卡片字段数据
            //List<CardTemplateStyleField> templateStyleFieldList = this.createTemplateStyleField(oldTemplateTableData.getBaseId(), dto.getUserId(), defaultTemplateId);

            // 5. 根据上面的模板，生成名片的具体数据，包括卡片字段和组件
            // 5.1 生成名片的卡片数据。根据表单里面填写的数据和默认模板上的字段属性按名字匹配，只保存能匹配上的
            this.createStyleFieldData(dto, cardBaseInfo.getBaseId(), dto.getTemplateStyleFieldList());
            // 5.2 生成名片的组件数据
            //this.createCardComponentData(templateComponentData, cardBaseInfo.getBaseId());
            // 生成名片的转发封面
            this.cardUserCardForwardCoverOptionService.createDefaultForwardCover(dto.getUserId(), cardBaseInfo.getBaseId(), cardShareConfig.getCoverUrl(), cardShareConfig.getType(), cardShareConfig.getCoverUrlBaseId());
            // 6. 将当前生成的名片设置为自动审核通过
            this.auditPass(luLianEnterprise.getBaseId(), templateId, cardBaseInfo.getBaseId(), dto.getUserId());
        }
        return Message.success();
    }


    private void auditPass(String enterpriseId, String templateId, String cardId, String userId) {
        CardAudit cardAudit = new CardAudit();
        cardAudit.setBaseId(IdUtil.simpleUUID());
        cardAudit.setEnterpriseId(enterpriseId);
        cardAudit.setTemplateId(templateId);
        cardAudit.setCardId(cardId);
        cardAudit.setCardStatus(NewCardBusinessConstant.CARD_STATUS_3);
        cardAudit.setBaseCreateBy(userId);
        cardAudit.setBaseUpdateBy(userId);
        cardAudit.setBaseCreateTime(new Date());
        cardAudit.setBaseUpdateTime(new Date());
        cardAudit.setActiveTime(new Date());
        cardAudit.setUserId(userId);
        cardAuditService.save(cardAudit);
    }

    // 生成名片的卡片字段数据
    private void createStyleFieldData(EnterpriseCardAddParamDto dto, String cardId, List<CardTemplateStyleField> cardTemplateStyleFields) {
        // 按名称匹配字段
        List<CardStyleFieldData> cardStyleFieldDataList = new ArrayList<>();
        for(CardTemplateStyleField cardTemplateStyleField: cardTemplateStyleFields) {
            if(cardTemplateStyleField.getBaseName().equals("姓名")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getName());
                cardStyleFieldDataList.add(fieldData);
            }else if(cardTemplateStyleField.getBaseName().equals("公司")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getEnterpriseName());
                cardStyleFieldDataList.add(fieldData);
            }else if(cardTemplateStyleField.getBaseName().equals("职位")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getPositionOne());
                cardStyleFieldDataList.add(fieldData);
            }else if(cardTemplateStyleField.getBaseName().equals("手机")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getEnterpriseMobile());
                cardStyleFieldDataList.add(fieldData);
            } else if(cardTemplateStyleField.getBaseName().equals("邮箱")) {
                CardStyleFieldData fieldData = new CardStyleFieldData();
                fieldData.setBaseId(IdUtil.simpleUUID());
                fieldData.setCardId(cardId);
                fieldData.setStyleFieldId(cardTemplateStyleField.getBaseId());
                fieldData.setStyleFieldValue(dto.getEnterpriseEmail());
                cardStyleFieldDataList.add(fieldData);
            }
        }
        if(CollectionUtil.isNotEmpty(cardStyleFieldDataList)) {
            cardStyleFieldDataService.saveBatch(cardStyleFieldDataList);
        }
    }

    // 创建名片的组件部分数据
    public void createCardComponentData(List<CardEnterpriseComponent> templateComponentData, String cardId) {
        if(CollectionUtil.isEmpty(templateComponentData)) {
            return;
        }
        List<CardComponentData> componentDataList = new ArrayList<>();
        for(CardEnterpriseComponent templateComponent : templateComponentData) {
            CardComponentData componentData = new CardComponentData();
            componentData.setBaseId(IdUtil.simpleUUID());
            componentData.setCardId(cardId);
            componentData.setTemplateComponentId(templateComponent.getBaseId());
            componentData.setComponentMetaData(templateComponent.getComponentMetaData());
            componentData.setSort(templateComponent.getSort());

            componentDataList.add(componentData);
        }
        cardComponentDataService.saveBatch(componentDataList);
    }

    // 创建模板的组件数据
    private List<CardEnterpriseComponent> createTemplateComponentData(String templateId, String defaultTemplateId) {
        List<CardEnterpriseComponent> templateComponentList = cardEnterpriseComponentMapper.queryCardEnterpriseComponentList(defaultTemplateId);
        if(CollectionUtil.isEmpty(templateComponentList)) {
            return null;
        }
        List<CardEnterpriseComponent> componentDataList = new ArrayList<>();
        for(CardEnterpriseComponent templateComponent : templateComponentList) {
            CardEnterpriseComponent newTemplateComponent = new CardEnterpriseComponent();
            newTemplateComponent.setBaseId(IdUtil.simpleUUID());
            newTemplateComponent.setTemplateId(templateId);
            newTemplateComponent.setComponentType(templateComponent.getComponentType());
            newTemplateComponent.setComponentMetaData(templateComponent.getComponentMetaData());
            newTemplateComponent.setComponentBusinessData(templateComponent.getComponentBusinessData());
            newTemplateComponent.setSort(templateComponent.getSort());
            newTemplateComponent.setComponentPermission(templateComponent.getComponentPermission());
            newTemplateComponent.setComponentPageId(IdUtil.simpleUUID());
            componentDataList.add(newTemplateComponent);
        }
        cardEnterpriseComponentService.saveBatch(componentDataList);
        return componentDataList;
    }

    private String createTemplateNew(String enterpriseId, EnterpriseCardAddParamDto dto, String defaultTemplateId) {
        String templateId = IdUtil.simpleUUID();
        CardEnterpriseTemplateNew defaultTemplateInfo = cardEnterpriseTemplateNewMapper.selectById(defaultTemplateId);
        if(defaultTemplateInfo == null) {
            throw new BusinessException("未查询到默认的模板信息");
        }
        CardEnterpriseTemplateNew newTemplate = new CardEnterpriseTemplateNew();
        BeanUtils.copyProperties(defaultTemplateInfo, newTemplate);
        newTemplate.setBaseId(templateId);
        newTemplate.setEnterpriseId(enterpriseId);
        newTemplate.setSourceTemplateId(defaultTemplateId);
        newTemplate.setVersion("2");
        newTemplate.setBaseUpdateBy(dto.getUserId());
        newTemplate.setBaseUpdateTime(new Date());
        newTemplate.setIsDelete(0);
        newTemplate.setBaseCreateBy(dto.getUserId());
        newTemplate.setBaseCreateTime(new Date());
        cardEnterpriseTemplateNewMapper.insert(newTemplate);
        return templateId;
    }

    // 创建老的模板表数据
    private CardEnterpriseTemplate createTemplate(String enterpriseId, EnterpriseCardAddParamDto dto, String newTemplateId, String defaultTemplateId) {
        String templateId = IdUtil.simpleUUID();
        CardEnterpriseTemplate defaultTemplateInfo = cardEnterpriseTemplateMapper.queryTemplateInfo(defaultTemplateId);
        if(defaultTemplateInfo == null) {
            throw new BusinessException("未查询到默认的模板信息");
        }
        CardEnterpriseTemplate template = new CardEnterpriseTemplate();
        BeanUtils.copyProperties(defaultTemplateInfo, template);
        template.setBaseId(templateId);
        template.setVersion("2");
        template.setEnterpriseId(enterpriseId);
        template.setUpdateBy(dto.getUserId());
        template.setBaseUpdateTime(new Date());
        template.setIsDelete("0");
        template.setCreator(dto.getUserId());
        template.setBaseCreateTime(new Date());
        template.setNewTemplateId(newTemplateId);
        return template;
    }

    private List<CardTemplateStyleField> createTemplateStyleField(String oldTemplateId, String userId, String defaultTemplateId, EnterpriseCardAddParamDto dto) {
        // 预设模板的字段属性
        CardEnterpriseTemplate defaultTemplateInfo = cardEnterpriseTemplateMapper.queryTemplateInfo(defaultTemplateId);
        List<CardTemplateStyleFieldBo> cardTemplateStyleFields = cardTemplateStyleFieldMapper.queryListByOldTemplateId(defaultTemplateInfo.getBaseId());
        List<CardTemplateStyleField> list = new ArrayList<>();
        for(CardTemplateStyleFieldBo templateStyleField : cardTemplateStyleFields) {
            CardTemplateStyleField newTemplateStyleField = new CardTemplateStyleField();
            BeanUtils.copyProperties(templateStyleField, newTemplateStyleField);

            newTemplateStyleField.setBaseId(IdUtil.simpleUUID());
            newTemplateStyleField.setTemplateId(oldTemplateId);
            newTemplateStyleField.setCreator(userId);
            newTemplateStyleField.setBaseCreateTime(new Date());
            newTemplateStyleField.setUpdateBy(userId);
            newTemplateStyleField.setBaseUpdateTime(new Date());
            JSONObject map = JSONObject.parseObject(templateStyleField.getExtraInfo(), JSONObject.class);
            // 回填表单上的手机、姓名、邮箱、公司等字段到新模板上
            if("姓名".equals(templateStyleField.getBaseName())) {
                map.put("text", dto.getName());
            }else if("公司".equals(templateStyleField.getBaseName())) {
                map.put("text", dto.getEnterpriseName());
            }else if("手机".equals(templateStyleField.getBaseName())) {
                map.put("text", dto.getEnterpriseMobile());
            }else if("邮箱".equals(templateStyleField.getBaseName())) {
                map.put("text", dto.getEnterpriseEmail());
            }else if("职位".equals(templateStyleField.getBaseName())) {
                map.put("text", dto.getPositionOne());
            }
            newTemplateStyleField.setExtraInfo(map);
            list.add(newTemplateStyleField);
        }
        if(!list.isEmpty()) {
            cardTemplateStyleFieldService.saveBatch(list);
        }
        return list;
    }

    private void bindEnterprise(String enterpriseId, String userId) {
        Integer count = luLianEnterpriseMapper.queryEnterpriseUserCount(enterpriseId, userId);
        if(count > 0) {
            return;
        }
        LuLianEnterpriseUser enterpriseUser = LuLianEnterpriseUser.builder().enterpriseId(enterpriseId).baseId(IdUtil.simpleUUID()).userId(userId).build();
        luLianEnterpriseUserMapper.insert(enterpriseUser);
    }

    private void setEnterpriseAdmin(String userId, String enterpriseId) {
        Integer count = luLianEnterpriseMapper.queryEnterpriseAdminCount(userId, enterpriseId);
        if(count > 0) {
            return;
        }
        newCardVersionMapper.insertEnterpriseAdmin(IdUtil.simpleUUID(), userId, enterpriseId);
    }

    private LuLianEnterpriseHistory buildEnterpriseHistoryInfo(EnterpriseCardAddParamDto dto) {
        Date now = new Date();
        LuLianEnterpriseHistory enterpriseHistory = new LuLianEnterpriseHistory();
        enterpriseHistory.setBaseId(IdUtil.simpleUUID());
        enterpriseHistory.setBaseName(dto.getEnterpriseName());
        enterpriseHistory.setIsAuth(false);
        enterpriseHistory.setExamineStatus("");
        enterpriseHistory.setStatus("1");
        enterpriseHistory.setCreator(dto.getUserId());
        enterpriseHistory.setBaseCreateTime(DateUtil.formatDateTime(now));
        enterpriseHistory.setEmail(dto.getEnterpriseEmail());
        return enterpriseHistory;
    }

    private CardBaseInfo buildEnterpriseCardInfo(EnterpriseCardAddParamDto dto, Date expireTime) {
        Date now = new Date();
        CardBaseInfo cardBaseInfo = new CardBaseInfo();
        String baseId = IdUtil.simpleUUID();
        cardBaseInfo.setBaseId(baseId);
        dto.setCardId(baseId);
        cardBaseInfo.setEnterpriseUseType(dto.getEnterpriseUseType());
        cardBaseInfo.setUserId(dto.getUserId());
        cardBaseInfo.setName(dto.getName());
        cardBaseInfo.setEnterpriseId(dto.getEnterpriseId());
        cardBaseInfo.setEnterpriseName(dto.getEnterpriseName());
        cardBaseInfo.setPositionOne(dto.getPositionOne());
        cardBaseInfo.setEnterpriseMobile(dto.getEnterpriseMobile());
        cardBaseInfo.setEnterpriseEmail(dto.getEnterpriseEmail());
        cardBaseInfo.setCardVersion(NewCardBusinessConstant.CARD_VERSION_2);
        cardBaseInfo.setExpireTime(expireTime);
        cardBaseInfo.setUseResourceType(NewCardBusinessConstant.CARD_USE_RESOURCE_TYPE_3);
        cardBaseInfo.setBaseCreateBy(dto.getUserId());
        cardBaseInfo.setBaseCreateTime(now);
        cardBaseInfo.setBaseUpdateBy(dto.getUserId());
        cardBaseInfo.setBaseUpdateTime(now);
        cardBaseInfo.setIsDelete(0);
        // 设置是否当前在用
        Integer currentUse = cardPersonalBaseInfoMapper.queryCurrentUseCardCount(dto.getUserId());
        cardBaseInfo.setCurrentUse(currentUse == 0 ? 1 : 0);
        return cardBaseInfo;
    }

    private void checkEnterpriseCardParam(EnterpriseCardAddParamDto dto) {
        if(StrUtil.isBlank(dto.getUserId())) {
            throw new BusinessException("用户ID不能为空");
        }
        if(StrUtil.isBlank(dto.getName())) {
            throw new BusinessException("姓名不能为空");
        }
        if(StrUtil.isBlank(dto.getEnterpriseName())) {
            throw new BusinessException("企业名称不能为空");
        }
        if(StrUtil.isBlank(dto.getPositionOne())) {
            throw new BusinessException("职位不能为空");
        }
        if(StrUtil.isBlank(dto.getEnterpriseMobile())) {
            throw new BusinessException("手机号码不能为空");
        }
    }
}
